﻿#include"test917.h"
#include"room.h"
#include<json\rapidjson.h>
#include<json\document.h>
#include"CommonFunction.h"


using namespace std;
Scene *test917::createscene()
{
	return test917::create();
}
bool test917::init()
{
	if (!Scene::init())
	{
		return false;
	}
	
	//加载素材
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("GameSence.plist", "GameSence.png");

	//注册触屏事件
	//事件监听器
	EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create();
	listener->onTouchMoved = CC_CALLBACK_2(test917::onTouchMoved, this);
	listener->onTouchBegan = CC_CALLBACK_2(test917::onTouchBegin,this);
	//把这个listener加入到事件派发器里
	Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener,this);

	CommonFunction::getChineseWithKey("b");

	Size visibleSize = Director::getInstance()->getVisibleSize();
	//游戏背景
	Sprite *background = Sprite::create("Background.png");
	background->setPosition(visibleSize.width / 2, visibleSize.height / 2);
	addChild(background);


	MenuItemFont *judgeItem = MenuItemFont::create("pd",CC_CALLBACK_1(test917::judgeItemChicked,this) );
	judgeItem->setPositionY(100);

	MenuItemFont *beginItem = MenuItemFont::create(CommonFunction::getChineseWithKey("beginGame")->getCString(), CC_CALLBACK_1(test917::beginGame, this));
	//返回
	MenuItemImage *closeItem = MenuItemImage::create("CloseNormal.png", "CloseSelected.png");
	closeItem->setCallback(CC_CALLBACK_1(test917::closeGameScene, this));
	closeItem->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT);
	closeItem->setPosition(Vec2(-visibleSize.width/2, visibleSize.height/2));
	closeItem->setScale(3);

	Menu *menu = Menu::create(closeItem, beginItem,judgeItem, NULL);
	addChild(menu);
	//创建自己
	self_pos = 3;
	for (int i = 1; i <= 4; i++)
	{
		Player *player = new Player();
		player->account = StringUtils::format("player%d", i);
		player->position = i;
		loadPlayerUI(player);

	}
	//创建按钮
	Button *showButton = Button::create("show_normal.png");
	showButton->setPosition(Vec2( visibleSize.width / 2-100, visibleSize.height / 2));
	showButton->setVisible(false);//隐藏
	showButton->setTag(100);
	showButton->addTouchEventListener(CC_CALLBACK_2(test917::buttonClicked,this));
	addChild(showButton);

	//创建不晒红十
	Button *unShowButton = Button::create("unShow_normal.png");
	unShowButton->setPosition(Vec2(visibleSize.width / 2 + 100, visibleSize.height / 2));
	unShowButton->setVisible(false);//隐藏
	unShowButton->setTag(200);
	unShowButton->addTouchEventListener(CC_CALLBACK_2(test917::buttonClicked, this));
	addChild(unShowButton);

	return true;
}
void test917::beginGame(Ref *pSender)
{
	Size visibleSize = Director::getInstance()->getVisibleSize();
	//如果之前有牌，清除后再开始
	if (game)
	{
		//因为game创建的时候，在构造器里创建了存放自己的节点
		game->selfCards_node->removeAllChildrenWithCleanup(true);
		CC_SAFE_DELETE(game);
		log("a");
		//之前的一些残留的内容需清除
		player_self->node->removeChildByTag(2);

	}


	log("游戏开始～～～");
	// 1.洗牌
	int cards[54];
	game = new CardGame();	
	game->shuffle(cards, 54);
	game->gameDidBegan = true; 

	// 2.发牌
	player_self->initCards();
	player_right->initCards();
	player_front->initCards();
	player_left->initCards();
	Player *currentPlayer; // 记录当前操作的玩家
	int start_pos = 3; // 先发给3号
	for (int i = 0; i < 54; i++) {
		// 获取当前发牌者的真实位置
		char pos_char = getPlayerCharPosition((start_pos + i - 1) % 4 + 1);

		// ♥️3
		if (cards[i] == 41) {
			game->first = pos_char;
		}
		// ♦️10
		if (cards[i] == 22) {
			game->red10_fk = pos_char;
		}
		// ♥️10
		if (cards[i] == 48) {
			game->red10_hx = pos_char;
		}

		switch (pos_char) {
		case 's':
			currentPlayer = player_self;
			break;
		case 'r':
			currentPlayer = player_right;
			break;
		case 'f':
			currentPlayer = player_front;
			break;
		case 'l':
			currentPlayer = player_left;
			break;
		default:
			break;
		}

		currentPlayer->cards[currentPlayer->countCards()] = cards[i];
	}

	//发牌结束位置
	//如果至少有一张红十在我自己这里，那需要显示晒不晒的按钮
	if (game->red10_fk == 's' || game->red10_hx == 's')
	{
		getChildByTag(100)->setVisible(true);
		getChildByTag(200)->setVisible(true);
	}
	else
	{
		getChildByTag(100)->setVisible(false);
		getChildByTag(200)->setVisible(false);
	}
	
	for (int i = 0; i < 14; i++)
	{
		player_self->cards[i] = i;
	}

	//给自己牌排序
	player_self->sortCards();
	//计算牌组放置的整体X轴居中位置
	int count = player_self->countCards();
	int mid = count / 2;
	float midx = (visibleSize.width + 180) / 2;

	// 显示自己的牌
	for (int i = 0; i < player_self->countCards(); i++) {

		Sprite *cardSprite = game->getCardSpriteWithValue(player_self->cards[i]);
		cardSprite->setScale(0.9);
		cardSprite->setPosition(Vec2(midx + 60 * (i - mid) + (count % 2 == 0 ? 30:0), cardSprite->getBoundingBox().size.height / 2 + 30));
		
		cardOriginY= cardSprite->getPositionY();

		game->selfCards_node->addChild(cardSprite);
	}
	addChild(game->selfCards_node);
}

void test917::setRoomId(int roomId)
{
	Label *label = Label::createWithSystemFont(StringUtils::format("room id=%d", roomId+1), "Arial", 40);
	Size visibleSize = Director::getInstance()->getVisibleSize();
	label->setAnchorPoint(Vec2::ANCHOR_TOP_RIGHT);
	label->setPosition(Vec2(visibleSize.width - 30, visibleSize.height - 30));
	label->enableOutline(Color4B(90, 221, 247, 255), 3);
	
	addChild(label);

}
void test917::closeGameScene(Ref *pSender)
{
	Director::getInstance()->replaceScene(room::createscene());
}
////加载对应玩家的UI信息
char test917::getPlayerCharPosition(int pos)
{
	if (self_pos == 1)//当自己坐在1
	{
		if (pos == 2)return'r';//2在右边
		if (pos == 3)return'f';//3在对面
		if (pos == 4)return'l';//4在左边 
	}
	else if (self_pos == 2)//当自己坐在2上
	{
		if (pos == 1)return'l';//1在左边
		if (pos == 3)return'r';//3在右边
		if (pos == 4)return'f';//4在对面
	}
	else if (self_pos == 3)//当自己坐在3上
	{
		if (pos == 1)return'f';//1在对面
		if (pos == 2)return'l';//3在左边
		if (pos == 4)return'r';//4在右边
	}
	else if (self_pos == 4)//当自己坐在4上
	{
		if (pos == 1)return'r';//1在右边
		if (pos == 2)return'f';//3在对面
		if (pos == 3)return'l';//4在左边
	}
	return's';//以上都不满足，则是自己
}
void test917::loadPlayerUI(Player *player)
{
	//将int的椅子号，转化为相对我所在的位置
	char pos_char1 = getPlayerCharPosition(player->position);
	log("%c", pos_char1);

	player->pos_char = pos_char1;

	player->createPlayerNode();
	addChild(player->node);

	switch (player->pos_char)
		{
		case's':
			player_self = player;
			break;
		case'r':
			player_right = player;
			break;
		case'f':
			player_front = player;
			break;
		case'l':
			player_left = player;
			break;
		}
}

bool test917::onTouchBegin(Touch *touch, Event *event)
{
	//获取点击位置
	Vec2 point= touch->getLocation();

	if (!game || game->gameDidBegan == false)
	{
		return true;
	}

	//遍历牌
	int count = player_self->countCards();
	bool didTouchCard = false;

	for (int i = 0; i < count; i++)
	{
		//获取当前遍历的那张牌的节点
		Node *card_node= game->selfCards_node->getChildByTag(player_self->cards[i]);

		//获取该节点的Rect
		Rect rect = card_node->getBoundingBox();

		//计算左侧区域
		Rect rectFortouch = Rect(rect.origin.x,rect.origin.y,60,rect.size.height);

		//最后一张，接收事件的范围应该是整个区域
		if (i == count - 1)
		{
			rectFortouch = rect;
		}

		//如果区域内包含了点击的点的位置，则找到了那张被点击的牌
		if (rectFortouch.containsPoint(point))
		{
			if (card_node->getPositionY() > cardOriginY)
			{
				card_node->setPositionY(cardOriginY);
			}
			else
			{
				card_node->setPositionY(cardOriginY + 30);
			}
			didTouchCard = true;
			break;
		}
	}

	if (didTouchCard)
	{
		log("1");
	}
	else
	{
		for (int i = 0; i < count; i++)
		{
			//找到牌，并缩进
			Node *cars_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
			cars_node->setPositionY(cardOriginY);
		}
	}
	return true;
}

void test917::onTouchMoved(Touch *touch, Event *event)
{
	Vec2 point = touch->getLocation();
	if (!game || game->gameDidBegan == false)
	{
		return ;
	}
	
	//遍历牌
	int count = player_self->countCards();
	for (int i = 0; i < count; i++)
	{
		//获取当前遍历的那张牌的节点
		Node *card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);

		//获取该节点的Rect
		Rect rect = card_node->getBoundingBox();

		//计算左侧区域
		Rect rectFortouch = Rect(rect.origin.x, rect.origin.y, 60, rect.size.height);

		//最后一张，接收事件的范围应该是整个区域
		if (i == count - 1)
		{
			rectFortouch = rect;
		}

		//如果区域内包含了点击的点的位置，则找到了那张被点击的牌
		if (rectFortouch.containsPoint(point))
		{
		  card_node->setPositionY(cardOriginY + 30);
			break;

		}
	}

}
void test917::buttonClicked(Ref *pSender, Widget::TouchEventType type)
{
	//处理结束事件
	if (type==Widget::TouchEventType::ENDED)
	{
		Button *btn = (Button *)pSender;
		switch (btn->getTag())
		{
		case 100:
		{
			int res = 0;
			if (game->red10_fk == 's'&&game->red10_hx == 's')
			{
				res = 3;
			}
			else if (game->red10_fk == 's')
			{
				res = 1;
			}
			else if (game->red10_hx == 's')
			{
				res = 2;
			}
			player_self->show(res);
			player_front->show(res);
			player_right->show(res);
			player_left->show(res);
			break;
		}
		case 200:
		
			break;
		default:
			break;
		}
		getChildByTag(100)->setVisible(false);
		getChildByTag(200)->setVisible(false);
	}
}
void test917::judgeItemChicked(Ref *pSender)
{
	//首先获取选择的牌是什么
	vector<int> arr;
	//遍历一遍牌的精灵，看看哪些牌弹出了
	for (int i = 0; i < player_self->countCards(); i++)
	{
		Node *card_node = game->selfCards_node->getChildByTag(player_self->cards[i]);
		if (card_node->getPositionY() > cardOriginY)
		{
			arr.push_back(player_self->cards[i]);
		}
	}
	PokerType type=game->getPokerTepyWithCards(arr);

	switch (type)
	{
	case POKER_TYPE_SINGLE:
		log("singler");
		break;
	case POKER_TYPE_KING_BOMB:
		log("king bomb");
		break;
	case POKER_TYPE_REDTEN_BOMB:
		log("red bomb");
		break;
	case POKER_TYPE_DOUBLE:
		log("double");
		break;
	case POKER_TYPE_THREE_BOMB:
		log("three bomb");
		break;
	case POKER_TYPE_FOUR_BOMB:
		log("four bomb");
		break;
	case POKER_TYPE_STRAIGHT:
	log("sz");
		break;
	default:
		log("牌型有误");
		break;
	}

	//检验
	for (int i = 0; i < arr.size(); i++)
	{
		log("%d", arr[i]);
	}
}